//
//  HomeStatusViewMedol.swift
//  微博
//
//  Created by mac on 15/12/20.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class HomeStatusViewMedol: NSObject {
    
    
    func loadStatus(since_id:Int64, max_id:Int64, finished:(statues:[Status]?)->()) {
        let urlStr = "2/statuses/friends_timeline.json"
        guard let token = UserAccontViewMedol().token else {
            SVProgressHUD.showWithStatus("请重新登录")
            return
        }
        var parameters = ["access_token":token]
        //传递属性
        //如果大于0,就添加属性
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id)"
        }
        print(token)
        NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlStr, parameters: parameters) { (result, error) -> () in
            guard let dict = result else{
                print("没有数据")
                finished(statues: nil)
                return
            }
            if let array = dict["statuses"] as? [[String : AnyObject]] {
                //遍历数组
                var list = [Status]()
                for item in array {
                    let medol = Status(dict: item)
                    list.append(medol)
                }
                //回调
                //不立即记性回调,先下载单张的图片
                self.cacheDownLoadImage(list, finished: finished)
//                finished(statues: list)
            }
        }
    }
    //创建群组对象buffer的池子 讲所有需要监听的异步方法方法哦任务池中
    private func cacheDownLoadImage(list: [Status],finished:(statues:[Status]?)->()) {
        //下载所有单张图片
        //如果是数组中没有图片,直接进行回调
        if list.count == 0 {
            finished(statues: list)
            return
        }
        //创建群组对象
        let group = dispatch_group_create()
        //遍历数组
        for s in list {
            //判断是不是单张图片
            if let urls = s.picURLs where urls.count != 1 {
                //跳出本次循环
                continue
            }
            //监听异步下载的属性
            dispatch_group_enter(group)
            //使用SDImage下载图片
            //使用sdimage去下载图片
            //回调的image,error,保存类型,是否成功,url
             SDWebImageManager.sharedManager().downloadImageWithURL(s.picURLs?.last, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                    //下载完成后出池
                print("单张图片下载完成")
                dispatch_group_leave(group)
             })
        }
        //群组任务监听的方法,在任务池中的任务为0时进行在主线程回调
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //所有图片下载完成
            print("又有图片下载完成")
            //回调方法
            finished(statues: list)
        }
        
        
        
        
    }
    
    
    
    
    
}
